package com.qili.quartz;

import cn.hutool.core.util.IdUtil;
import com.qili.base.entity.CurrentUser;
import com.qili.core.utils.DictTypes;
import com.qili.entity.affaircase.AffairCase;
import com.qili.entity.affaircase.AffairRecord;
import com.qili.entity.affaircase.dto.AffairCaseDTO;
import com.qili.entity.affaircase.dto.AffairRecordDTO;
import com.qili.entity.base.BaseDict;
import com.qili.entity.supervisor.SupervisorFileTemp;
import com.qili.entity.supplier.SupplierProject;
import com.qili.service.AffairService;
import com.qili.service.SysUserService;
import com.qili.service.WorkflowService;
import com.qili.service.affairCase.AffairCaseService;
import com.qili.service.affairCase.AffairRecordService;
import com.qili.service.base.BaseCompanyService;
import com.qili.service.base.BaseDictService;
import com.qili.service.supervisor.ProjectNoticeServie;
import com.qili.service.supervisor.SupervisorFileTempService;
import com.qili.service.supplier.SupplierProjectAcceptService;
import com.qili.service.supplier.SupplierProjectManagerService;
import com.qili.service.supplier.SupplierProjectPubNoticeService;
import com.qili.util.CommonUtil;
import com.qili.util.DateUtil;
import lombok.extern.java.Log;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zhaoyongke 供需发布项目自动审核
 * 后台设置供需项目审核时间（小时为单位），超过审核时间则默认审核通
 * @date 2021/4/7
 * @description
 */
@Log
public class GxCheckJob implements Job {
    @Autowired
    SysUserService sys;
    @Autowired
    private SupplierProjectPubNoticeService supplierProjectPubNoticeService;
    @Autowired
    private SupplierProjectManagerService supplierProjectManagerService;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    ProjectNoticeServie projectNoticeServie;
    @Autowired
    SupplierProjectAcceptService supplierProjectAcceptService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    BaseCompanyService baseCompanyService;
    @Autowired
    AffairService affairService;
    @Autowired
    AffairCaseService affairCaseService;
    @Autowired
    WorkflowService workflowService;
    @Autowired
    AffairRecordService affairRecordService;

    @Autowired
    SupervisorFileTempService supervisorFileTempService;


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("JobDemo1：启动任务=======================");
        run();
        System.out.println("JobDemo1：下次执行时间=====" +
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
                        .format(context.getNextFireTime()) + "==============");
    }

    public void run() {

        saveSendCheck();
    }

    public void saveSendCheck() {

        try {
            String wyvalue = "";
            List<BaseDict> typeListSsbl = baseDictService.selectByTypeCode(DictTypes.GXCHECK001.getType());
            if (typeListSsbl.size() > 0) {
                BaseDict bzjbl = typeListSsbl.get(0);
                wyvalue = bzjbl.getBadtLevel1();
            }
            AffairCaseDTO caseDTO = new AffairCaseDTO();
            List<AffairCaseDTO> affairCaseDTOS = affairService.queryTodoGxShZdCheck(caseDTO);
            log.info("开始进入自动审核111");

            for (int i = 0; i < affairCaseDTOS.size(); i++) {
                log.info("开始进入自动审核222222222222222222222222222222222222222222222222222222222222");
                AffairCaseDTO affairCaseDTO = affairCaseDTOS.get(i);
                String businessId = affairCaseDTO.getBusinessId();
                String caseId = affairCaseDTO.getCaseId();
                String processInstanceId = affairCaseDTO.getProcessInstanceId();
                //流程变量
                Map<String, Object> variables = new HashMap<String, Object>();

                SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(businessId);
                // 2021-04-15 10:36:14
                String acceptTimestr = affairCaseDTO.getAcceptTime();
                Date acceptTime = DateUtil.parseDate(acceptTimestr, "yyyy-MM-dd HH:mm:ss");

                Calendar calendar = new GregorianCalendar();
                calendar.setTime(acceptTime);
                calendar.add(Calendar.HOUR, Integer.valueOf(wyvalue));
                /*获得推荐日期y天后的日期*/
                Date dateafterx = new Date(calendar.getTimeInMillis());
                Date currdate = new Date();
                System.out.println("进入时间");
                if (currdate.after(dateafterx)) {
                    log.info("开始进入自动审核3333333333333333333333333333333333333333333333333333333333333");
                    System.out.println("进入时间1=========================");
                    // 自动完成任务
                    String status = project.getStatus();
                    if ("006".equals(status)) {
                        //提交后从临时文件表 移动到正式文件表中
                        String copyZskUrl = supervisorFileTempService.getCopyZskUrl(project);
                        SupervisorFileTemp temp = new SupervisorFileTemp();
                        temp.setLinkId(project.getSupProjectId());
                        List<SupervisorFileTemp> selectfilelist = supervisorFileTempService.select(temp);
                        supervisorFileTempService.updateCopyFileToZsk(copyZskUrl, project, selectfilelist);
                        project.setZskurl(copyZskUrl);
                        affairService.updateGxChangeProject("2", project, "xt");
                        log.info("开始进入自动审核4444444444444444444444444444444444444444444444444444444444444444444444444444");
                        System.out.println("进入时间2============2222222=============" + affairCaseDTO.getCaseName());
                    } else {
                        //提交后从临时文件表 移动到正式文件表中
                        String copyZskUrl = supervisorFileTempService.getCopyZskUrl(project);
                        SupervisorFileTemp temp = new SupervisorFileTemp();
                        temp.setLinkId(project.getSupProjectId());
                        List<SupervisorFileTemp> selectfilelist = supervisorFileTempService.select(temp);
                        supervisorFileTempService.updateCopyFileToZsk(copyZskUrl, project, selectfilelist);
                        project.setZskurl(copyZskUrl);
                        project.setStatus("006");//已发布
                        project.setPublishDate(DateUtil.getCurrentDateString());
                        log.info("开始进入自动审核555555555555555555555555555555555555555555555555555555555555555555555555555555555555");
                        System.out.println("进入时间3=============3333============" + affairCaseDTO.getCaseName());
                    }
                    project.setCheckStatus("2");
                    project.setCheckRemark("2");
                    String currentDateString = DateUtil.getCurrentDateString();
                    project.setCheckDate(currentDateString);
                    project.setCheckBy("admin");
                    supplierProjectManagerService.updateByPrimaryKey(project);
                    AffairCase affairCase = new AffairCase();
                    affairCase.setCaseId(caseId);
                    affairCase = affairCaseService.selectByPrimaryKey(affairCase);
                    // 完成任务
                    AffairCaseDTO act = new AffairCaseDTO();
                    act.setProcessInstanceId(affairCaseDTOS.get(i).getProcessInstanceId());
                    List<AffairCaseDTO> listcase = affairService.queryAruTask(act);
                    String record = "";
                    if (!CollectionUtils.isEmpty(listcase)) {
                        String taskId = listcase.get(0).getTaskId();
                        workflowService.completeTask(taskId, false, variables);
                        record = addAffairCaseRecord(caseId, "002", "发布审核", "2", "", taskId, processInstanceId);
                    }
                    System.out.println("进入时间3=============777777777============" + affairCaseDTO.getCaseName());
                    //更新AffirCase
                    updateAffirCase(affairCase, true, record, "2", "系統自动审核");
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }


    }

    /**
     * @param affairCase
     * @Author:zhaoyongke
     * @Description: 更新affircase
     * @Date:17:01 2020/12/8
     */
    public void updateAffirCase(AffairCase affairCase, Boolean isfinsih, String recordId, String checkStatus, String remark) {
        if (isfinsih) {
            affairCase.setEndresult("1");
            affairCase.setEndTime(DateUtil.formatDate(new Date()));
            if ("3".equals(checkStatus)) {
                //审核不通过 审核备注
                affairCase.setMemo(remark);
            }
        }

        affairCase.setCurrRecordId(recordId);
        affairCaseService.updateByPrimaryKey(affairCase);
    }

    public String addAffairCaseRecord(String ywId, String ywType, String hjName, String checkStatus, String remark, String taskId, String processInstanceId) {
        AffairRecordDTO dto = new AffairRecordDTO();
        // 业务Id
        dto.setYwId(ywId);
        /**
         * 业务类型 001 监理系统 002 供需 0
         */
        dto.setYwType(ywType);
        //环节名称
        dto.setHjName(hjName);
        //审核状态 1 提交 2 审核通过 3 审核不通过

        dto.setCheckStatus(checkStatus);
        //备注
        dto.setRemark(remark);
        // 任务id
        dto.setTaskId(taskId);
        // 工作流实例id
        dto.setProcessInstanceId(processInstanceId);
        String recordId = addAffairCaseRecord(dto);
        return recordId;

    }

    public String addAffairCaseRecord(AffairRecordDTO dto) {

        AffairRecord affairRecord = new AffairRecord();
        affairRecord.setRecordId(IdUtil.simpleUUID());
        //业务表主键
        affairRecord.setYwId(dto.getYwId());
        /**
         * 业务类型 001 监理系统 002 咨询 003 检测
         */
        affairRecord.setYwType(dto.getYwType());
        //环节名称
        affairRecord.setHjName(dto.getHjName());
        //审核状态 1 提交 2 审核通过 3 审核不通过
        affairRecord.setCheckStatus(dto.getCheckStatus());
        //备注
        affairRecord.setRemark(dto.getRemark());
        //操作人
        affairRecord.setOperUserId("admin");
        //操作时间
        affairRecord.setOperDate(DateUtil.formatDate(new Date()));
        // 任务id
        affairRecord.setTaskId(dto.getTaskId());
        // 工作流实例id
        affairRecord.setProcessInstanceId(dto.getProcessInstanceId());

        affairRecordService.insert(affairRecord);
        return affairRecord.getRecordId();
    }


}
